package com.xxxx.yoyo.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxx.yoyo.bean.Goods;
import com.xxxx.yoyo.bean.Order;
import com.xxxx.yoyo.bean.User;
import com.xxxx.yoyo.service.IGoodsService;
import com.xxxx.yoyo.service.IOrderService;
import com.xxxx.yoyo.service.impl.GoodsServiceImpl;
import com.xxxx.yoyo.service.impl.OrderServiceImpl;

/**
 * Servlet implementation class LessenGoodsFromOrderServlet
 */
@WebServlet("/index/lessen")
public class LessenGoodsFromCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IGoodsService goodsService = new GoodsServiceImpl();
	private IOrderService orderService = new OrderServiceImpl();
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取session
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user == null) {//如果session失效了(有效期默认是30分钟). user就获取不到了
			//返回login, 让前端去登录
			response.getWriter().append("login");
		}else {//session还没有失效. user以及order都还存储在session中
			//获取虚拟订单order
			Order order = (Order)session.getAttribute("order");
			
			//提取前端传递过来的参数goodid
			String goodsIdStr = request.getParameter("goodid");
			int goodsId = Integer.parseInt(goodsIdStr);
			//根据宠物的id查询宠物
			Goods goods = goodsService.getGoodsById(goodsId);
			
			//从订单中减少宠物
			boolean isOrderEmpty = orderService.lessenGoodsFromOrder(goods, order);
			
			if(isOrderEmpty) {//删除虚拟订单,让购物车页面显示"空空如也"
				session.removeAttribute("order");
			}
			
			//返回ok, 表示操作成功
			response.getWriter().append("ok");
		}
		
	}

}
